package com.zunipe.chat.util;

import java.io.IOException;
import java.io.InputStream;

public class EncodeHelper {
    public static final int HEAD_SIZE = 4;

    public static byte[] toBytes(String context) {
        byte[] bodyByte = context.getBytes();
        int bodyByteLength = bodyByte.length;
        byte[] result = new byte[HEAD_SIZE + bodyByteLength];
        // 将消息体长度写入消息头
        result[0] = (byte) (bodyByteLength >> 24);
        result[1] = (byte) (bodyByteLength >> 16);
        result[2] = (byte) (bodyByteLength >> 8);
        result[3] = (byte) (bodyByteLength);
        // 将消息体写入结果数组
        System.arraycopy(bodyByte, 0, result, HEAD_SIZE, bodyByteLength);
        return result;
    }

    public static int getHeader(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[HEAD_SIZE];
        inputStream.read(bytes, 0, HEAD_SIZE);
        return ((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | ((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF);
    }
}
